/* $RCSFile: CrmInputIncident.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmInputIncident/CrmInputIncident.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:19  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:50  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Authentication;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CrmInputIncident
{

 	#region Local TraceSwitch 
	public class CrmIncidentTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("CrmInputIncidentTrace","Special Trace Switch for CrmInputIncident");
	}
	#endregion Local TraceSwitch 

    public class AStr
    {
        public const string CrmInputIncidentOwner        =   "INCIDENT_INPUT_OWNER";
        public const string AssignToOwner                =   "INCIDENT_INPUT_OWNER_AUTOASSIGN";
        public const string AutoCreateIfNotExists        =   "INCIDENT_INPUT_CREATE_IF_NOTEXISTS";
        public const string UseCustomerFilter            =   "INCIDENT_INPUT_USE_CUSTOMER_FILTER";
        public const string CustomerFilter               =   "INCIDENT_INPUT_CUSTOMER_FILTER";
        public const string UserQueryMode                =   "INCIDENT_INPUT_USERQUERY_MODE";
        public const string UserQuery                    =   "INCIDENT_INPUT_USERQUERY";

        public const string AutoCustomer                 =   "INCIDENT_INPUT_CUSTOMER_AUTOASSIGN";
        public const string DefaultCustomer              =   "INCIDENT_INPUT_DEFAULT_CUSTOMER";
        public const string InputContract                =   "INCIDENT_INPUT_INPUT_CONTRACT";
    }

    /// <summary>
    /// Initializer class for CrmInputIncident 
    /// </summary>
    public class CrmInputIncidentSI : PortalCRMModuleControlSI
    {
        public CrmInputIncidentSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputIncidentSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputIncidentSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputIncidentSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string resFile	                            =	"CrmInputIncident";
			// Specific parameters
            string extgrp                               =   pm.ExtendedResourcesGroup;
            
            SettingItemSpecial AttributeOwner           =   new SettingItemSpecial(AStr.AssignToOwner,new BooleanDataType());
            AttributeOwner.Required                     =   false;
			AttributeOwner.ResourceFile                 =   resFile;
            AttributeOwner.Value                        =   StStr.strFalse;
            AttributeOwner.Order                        =   10;
            AttributeOwner.ExtendedGroupName            =   extgrp;
            AttributeOwner.EnglishName                  =   "Assign to Owner";
            AttributeOwner.Description                  =   "When checked, the new incidents will be automatically assigned to selected owner";
            bSettings.AddSetting(AttributeOwner);

            WSListDataType defAcc                       =   new WSListDataType(CrmStr.systemuser,StStr.smName,StStr.bgID);
            SettingItemSpecial ModuleOwner              =   new SettingItemSpecial(AStr.CrmInputIncidentOwner,defAcc);
            // default == CRMDefaultAccount or first
            ADNDynSystemUser wsys                       =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName                       =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                                    =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            else 
            {
                wsys                                    =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),Wrapper.adminUserId);
            }
            if (wsys != null)
            {
                ModuleOwner.Value                       =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue                 =   wsys.fullname;
            }
            ModuleOwner.EnglishName                     =   "Owner";
            ModuleOwner.ResourceFile                    =   resFile;
            ModuleOwner.Order                           =   20;
            ModuleOwner.ExtendedGroupName               =   extgrp;
            ModuleOwner.Description                     =   "Choose the owner for Incidents created with this module if specified by previous ckeckbox";
            ModuleOwner.SettingItemsEvent               +=  new SettingItemsEventHandler(ModuleOwner_SettingItemsEvent);
            bSettings.AddSetting(ModuleOwner);

            // Use a fixed Customer, so don't select it from input
            SettingItemSpecial FixedCustomer            =   new SettingItemSpecial(AStr.AutoCustomer,new BooleanDataType());
            FixedCustomer.Required                      =   false;
			FixedCustomer.ResourceFile                  =   resFile;
            FixedCustomer.Value                         =   StStr.strFalse;
            FixedCustomer.Order                         =   22;
            FixedCustomer.ExtendedGroupName             =   extgrp;
            FixedCustomer.EnglishName                   =   "Don't input customer";
            FixedCustomer.Description                   =   "When checked, the customer will not be input but autoassigned to current user";
            bSettings.AddSetting(FixedCustomer);

            // to create the nonexisting accounts automatically
            SettingItemSpecial AutoCreateCompany        =   new SettingItemSpecial(AStr.AutoCreateIfNotExists,new BooleanDataType());
            AutoCreateCompany.Required                  =   false;
            AutoCreateCompany.ResourceFile              =   resFile;
            AutoCreateCompany.Value                     =   StStr.strFalse;
            AutoCreateCompany.Order                     =   30;
            AutoCreateCompany.ExtendedGroupName         =   extgrp;
            AutoCreateCompany.EnglishName               =   "Create Customer";
            AutoCreateCompany.Description               =   "When checked the nonexisting customer is automatically created.";
            bSettings.AddSetting(AutoCreateCompany);

            // Don't input contract
            SettingItemSpecial InputContract            =   new SettingItemSpecial(AStr.InputContract,new BooleanDataType());
            InputContract.Required                      =   false;
			InputContract.ResourceFile                  =   resFile;
            InputContract.Value                         =   StStr.strFalse;
            InputContract.Order                         =   32;
            InputContract.ExtendedGroupName             =   extgrp;
            InputContract.EnglishName                   =   "Input contract";
            InputContract.Description                   =   "When checked, input contract and line";
            bSettings.AddSetting(InputContract);

            defAcc                                      =   new WSListDataType(CrmStr.contact,StStr.smName,StStr.bgID);
            defAcc.NeedDisplayTextEvent                 +=  new NeedDisplayTextEventHandler(DefaultCustomer4Incident_NeedDisplayTextEvent);
	        SettingItemSpecial DefaultCustomer4Incident =   new SettingItemSpecial(AStr.DefaultCustomer,defAcc);
            defAcc.DisplayTextValue                     =   string.Empty;

            DefaultCustomer4Incident.Value              =   Guid.Empty.ToString(); // we need to set a default value even if not installed
            DefaultCustomer4Incident.Required           =   false;
			DefaultCustomer4Incident.ResourceFile       =   resFile;
            DefaultCustomer4Incident.Order              =   35;
            DefaultCustomer4Incident.ExtendedGroupName  =   extgrp;
            DefaultCustomer4Incident.EnglishName        =   "Default customer";
            DefaultCustomer4Incident.Description        =   "When in AD authentication or Anonymous user, use this default contact for incidents";
            //DefaultCustomer4Incident.SettingItemsEvent     += new SettingItemsEventHandler(DefaultCustomer4Incident_SettingItemsEvent);

            bSettings.AddSetting(DefaultCustomer4Incident);


            // to filter customers when input
            SettingItemSpecial UseCustomerFilter        =   new SettingItemSpecial(AStr.UseCustomerFilter,new BooleanDataType());
            UseCustomerFilter.Required                  =   false;
            UseCustomerFilter.ResourceFile              =   resFile;
            UseCustomerFilter.Value                     =   StStr.strFalse;
            UseCustomerFilter.Order                     =   40;
            UseCustomerFilter.ExtendedGroupName         =   extgrp;
            UseCustomerFilter.EnglishName               =   "Create Customer";
            UseCustomerFilter.Description               =   "When checked the nonexisting customer is automatically created.";
            bSettings.AddSetting(UseCustomerFilter);

            SettingItemSpecial FirstQueryMode           =   new SettingItemSpecial(AStr.UserQueryMode,new BooleanDataType());
            FirstQueryMode.Value                        =   StStr.strTrue;
            FirstQueryMode.ResourceFile                 =   resFile;
            FirstQueryMode.Order                        =   50;
            FirstQueryMode.ExtendedGroupName            =   extgrp;
            FirstQueryMode.EnglishName                  =   "Use Xml request";
            FirstQueryMode.Description                  =   "If checked use Fetch Xml request else use a saved user query.";
            bSettings.AddSetting(FirstQueryMode);

            CustomListDataType gdt                      =   new CustomListDataType(null,CrmStr.name,CrmStr.userqueryid);
            gdt.NeedDataEvent                           +=  new NeedDataEventHandler(CrmHelper.BuildAccountQueryTable);

            SettingItemSpecial FirstQuery               =   new SettingItemSpecial(AStr.UserQuery,gdt);
            FirstQuery.Value                            =   string.Empty;
            FirstQuery.ResourceFile                     =   resFile;
            FirstQuery.Order                            =   60;
            FirstQuery.ExtendedGroupName                =   extgrp;
            FirstQuery.EnglishName                      =   "First query";
            FirstQuery.Description                      =   "Select the first query";
            bSettings.AddSetting(FirstQuery);

            SettingItemSpecial FirstQueryXml            =   new SettingItemSpecial(AStr.CustomerFilter,new StringDataType(10));
            FirstQueryXml.ResourceFile                  =   resFile;
            FirstQueryXml.Order                         =   70;
            FirstQueryXml.ExtendedGroupName             =   extgrp;
            FirstQueryXml.EnglishName                   =   "Fetch Xml for Query";
            FirstQueryXml.Description                   =   "Enter the XML content for query";
            bSettings.AddSetting(FirstQueryXml);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputIncidentSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
        
        /// <summary>
        /// Called by the webService RadCombo to display some text
        /// </summary>
        void DefaultCustomer4Incident_NeedDisplayTextEvent(object sender,WSListEventArgs e)
        {
            if ( CrmIncidentTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncidentSI DefaultCustomer4Incident_NeedDisplayTextEvent Guid: {0}", e.Val),CrmIncidentTrace.Sw.Info);
            Guid custId                     =   new Guid((string)e.Val);
            if ( custId == Guid.Empty )
                return;
            DynEntity dynac                 =   null;
            switch ( e.entityName )
            {
                case CrmStr.account:
                dynac                       =   DynEntity.GetFromCache<ADNDynAccount>(CrmStr.account,Wrapper,ResetWrapper,custId);
                break;
                case CrmStr.contact:
                dynac                       =   DynEntity.GetFromCache<ADNDynContact>(CrmStr.contact,Wrapper,ResetWrapper,custId);
                break;
                default:
                return;
            }
            WSListDataType defAcc           =   (WSListDataType )sender;
            switch ( e.entityName )
            {
                case CrmStr.account:
                    defAcc.DisplayTextValue =   dynac.name;
                break;
                case CrmStr.contact:
                    defAcc.DisplayTextValue =   dynac.fullname;
                break;
            }
            if ( CrmIncidentTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncidentSI DefaultCustomer4Incident_NeedDisplayTextEvent END name: {0}", dynac.name),CrmIncidentTrace.Sw.Info);
        }

        /// <summary>
        /// Used to set the good display value in ModuleOwner when loaded from DB
        /// </summary>
        void ModuleOwner_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( CrmIncidentTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncidentSI ModuleOwner_SettingItemsEvent Guid: {0}", e.Data),CrmIncidentTrace.Sw.Info);
            Guid custId                 =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynSystemUser dynac      =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defAcc       =   (WSListDataType )((SettingItem)sender).DataType;
            defAcc.DisplayTextValue     =   dynac.fullname;
            if ( CrmIncidentTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncidentSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),CrmIncidentTrace.Sw.Info);
        }
    }

    public partial class CrmInputIncident : PortalCRMModuleControl
    {
        #region General implementation

        public override Guid GuidID
        {
            get
            {
                return new Guid("{C57020CE-9DA3-4e6e-908B-59072E652ADC}");
            }
        }
        #endregion General implementation

        /// <summary>
        /// Ctor
        /// </summary>
        public CrmInputIncident()
        {
            // Validators : name Ok
            ValidationGroup         =   "Main";
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                         =   "INPUTCRMINCIDENT";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmInputIncidentSI(bSettings,this);
        }

    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident Page_Load isPostBack: {0}",IsPostBack),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            if (!IsPostBack)
            {
                if ( Settings[AStr.AutoCreateIfNotExists].ToBool() )
                     RequiredCustomer.Enabled   =   true;
                else RequiredCustomer.Enabled   =   false;

                Style nst                       =   new Style();
                nst.ForeColor                   =   Color.Red;
                lblTitle.ForeColor              =   Color.Red;
                LoadPickList(CrmStr.caseorigincode,ComboOrigin);
                LoadPickList(CrmStr.prioritycode,ComboPriority);
                LoadPickList(CrmStr.contractservicelevelcode,ComboServiceLevel);
                LoadPickList(CrmStr.customersatisfactioncode,ComboStatisfaction);
                LoadPickList(CrmStr.casetypecode,ComboType);
                if ( !Settings[AStr.AutoCustomer].ToBool() )
                    LoadCustomers();
                LoadLookup(CrmStr.subject,ComboSubject,null);
                LoadLookup(CrmStr.product,ComboProduct,null);
            }
        }


        #region insert input in Crm


        bool AttachNote(ADNDynIncident ic,UploadedFile fi)
        {
            try
            {
                string fileName         =   fi.GetNameWithoutExtension();
                if (CrmIncidentTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident AttachNote BEG FileName: '{0}'.",fileName),CrmIncidentTrace.Sw.Info);
                // Now create the annotation object. 
                ADNDynAnnotation note   =   new ADNDynAnnotation(Wrapper,string.Format("Document {0}",fileName));
                note.SetOwnerFromUserId();
                note.notetext           =   string.Format("Document downloaded with incident {0}",ic.ticketnumber);
                note.subject            =   fileName;
                note.DefaultObjectName  =   CrmStr.incident;
                note.objectid           =   ic.incidentid;
                note.objecttypecode     =   CrmStr.incident;

                // Create the note.
                note.adminCreate();

                // read the contents into a byte array.
                Stream istream          =   fi.InputStream;
                byte[] byteData         =   new byte[istream.Length];
                istream.Read(byteData, 0, byteData.Length);

                // Encode the data using base64.
                string encodedData      =   System.Convert.ToBase64String(byteData);

                // Now update the note.
                note.documentbody       =   encodedData;
                note.filename           =   fi.GetName();
                note.mimetype           =   fi.ContentType;
                note.adminUpdate();
                if (CrmIncidentTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident AttachNote END FileName: '{0}'.",fileName),CrmIncidentTrace.Sw.Info);
            }
            catch(Exception ex)
            {
                if (CrmIncidentTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident AttachNote ex: '{0}'.",ex),CrmIncidentTrace.Sw.Info);
                return false;
            }
            return true;
        }

        /// <summary>
        /// Tasks to do:
        /// 0) validate datas
        /// 1) Insert record in CRM
        /// 2) insert record in DB
        /// </summary>
        void CrmInputIncident_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            bool autoAssignCustomer =   Settings[AStr.AutoCustomer].ToBool();
            if ( !autoAssignCustomer &&
                     (ComboCustomer.SelectedIndex == -1) && !Settings[AStr.AutoCreateIfNotExists].ToBool() )
            {
                if (CrmIncidentTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmInputIncident CrmInputIncident_ADNUpdateModule cancelled: !AutoCreateIfNotExists && no selectedCustomer.",CrmIncidentTrace.Sw.Info);
                LblTicketNumber.Text        =   LocalizeHelper.Localize("INCIDENT_INPUT_NOCUSTOMER","Customer is required");
                e.Cancel                    =   true;
                return;
            }
            // Add new Incident 
            ADNDynIncident im                =   null;
            try
            {
                string title                =   RadtxtTitle.Text.Trim();
                im                          =   new ADNDynIncident(PortalSecurity.Wrapper,title);
                im.SetOwnerFromUserId();
                im.customersatisfactioncode =   int.Parse(ComboStatisfaction.SelectedValue);
                im.prioritycode             =   int.Parse(ComboPriority.SelectedValue);
                im.caseorigincode           =   int.Parse(ComboOrigin.SelectedValue);
                im.casetypecode             =   int.Parse(ComboType.SelectedValue);
                if ( DateFollowUp.SelectedDate.HasValue )
                    im.followupby               =   DateFollowUp.SelectedDate.Value.ToString();
                
                if (CrmIncidentTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule ComboCustomer.SelectedValue: '{0}'.",ComboCustomer.SelectedValue.ToString()),CrmIncidentTrace.Sw.Info);
                if ( !autoAssignCustomer )
                {
                    if ( ComboCustomer.SelectedIndex == -1 )
                    {
                        im.customerid               =   Guid.Empty;
                        // If the Company Name is not empty checks the existence of the company
                        string searchedCustomer     =   ComboCustomer.Text.Trim();
                        bool parentCreated          =   false;
                        if ( CrmIncidentTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule searching for Customer: '{0}'.",searchedCustomer),CrmIncidentTrace.Sw.Info);
                        if ( searchedCustomer != string.Empty )
                        {
                            ADNDynAccount s         =   Wrapper.Util.FindAccountByName(searchedCustomer,true,ref parentCreated);
                            if ( s != null )
                                im.customerid       =   s.accountid;
                            else
                            {
                                e.Cancel = true;
                                return;
                            }
                        }

                    }
                    else
                        im.customerid               =   new Guid(ComboCustomer.SelectedValue);
                }
                else //autoAssignCustomer
                {
                    Guid defaultCustomerId          =   Settings[AStr.DefaultCustomer].ToGuid();
                    if ( CrmIncidentTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule usr defaultCustomerId: {0}",defaultCustomerId),CrmIncidentTrace.Sw.Info);
                    if ( Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Forms )
                    {
                        AddonNiceMembershipUser usr =   (AddonNiceMembershipUser)Membership.GetUser(PortalSettings.CurrentIdentity.Name);
                        if ( CrmIncidentTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule usr null: {0}",(usr == null)),CrmIncidentTrace.Sw.Info);
                        if ( usr != null )
                        {
                            im.DefaultCustomerName  =   usr.CustomerId.typeName;
                            im.customerid           =   usr.CustomerId.CrmId;
                            if ( CrmIncidentTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule account assigned to typeName: {0}', id: {1}.",
                                    usr.CustomerId.typeName,usr.CustomerId.CrmId),CrmIncidentTrace.Sw.Info);
                        }
                        else
                        {
                            im.DefaultCustomerName  =   CrmStr.contact;
                            im.customerid           =   defaultCustomerId;
                        }
                    }
                    else // TBD: transfer default assign account from E-Commerce to main portal and use it
                    {
                        im.DefaultCustomerName      =   CrmStr.contact;
                        im.customerid               =   defaultCustomerId;
                    }
                }
                if (CrmIncidentTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule ComboSubject.SelectedValue: '{0}'.",ComboSubject.SelectedValue.ToString()),CrmIncidentTrace.Sw.Info);
                if ( !string.IsNullOrEmpty(ComboSubject.SelectedValue))
                {
                    Guid Subjectid                  =   new Guid(ComboSubject.SelectedValue);
                    if (Subjectid != Guid.Empty)
                        im.subjectid                =   Subjectid;
                }
                if (CrmIncidentTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule ComboContract.SelectedValue: '{0}'.",ComboContract.SelectedValue.ToString()),CrmIncidentTrace.Sw.Info);
                if (  Settings[AStr.InputContract].ToBool() && !string.IsNullOrEmpty(ComboContract.SelectedValue))
                {
                    Guid Contractid                 =   new Guid(ComboContract.SelectedValue);
                    if (Contractid != Guid.Empty)
                    {
                        if (CrmIncidentTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule ComboContractLine.SelectedValue: '{0}'.",ComboContractLine.SelectedValue.ToString()),CrmIncidentTrace.Sw.Info);
                        if (!string.IsNullOrEmpty(ComboContractLine.SelectedValue))
                        {
                            Guid ContractDetailid   =   new Guid(ComboContractLine.SelectedValue);
                            if (ContractDetailid != Guid.Empty)
                            {
                                im.contractid       =   Contractid;
                                im.contractdetailid =   ContractDetailid;
                            }
                        }
                    }
                }
                if (CrmIncidentTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule ComboProduct.SelectedValue: '{0}'.",ComboProduct.SelectedValue.ToString()),CrmIncidentTrace.Sw.Info);
                if ( ! string.IsNullOrEmpty(ComboProduct.SelectedValue) )
                {
                    Guid Productid                  =   new Guid(ComboProduct.SelectedValue);
                    if ( Productid != Guid.Empty )
                        im.productid                =   Productid;
                }

                im.contractservicelevelcode         =   int.Parse(ComboServiceLevel.SelectedValue);

                im.productserialnumber              =   TbSerialNumber.Text.Trim();
                im.description                      =   RadTextDescription.Text.Trim();

                // Create in CRM using web service
                try
                {
                    Guid IncidentID                 =  im.adminCreate();
                    if (CrmIncidentTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule Incident created IncidentID: {0}", IncidentID),CrmIncidentTrace.Sw.Info);
                    im.adminRetrieve();
                    LblTicketNumber.Text            =   im.ticketnumber;
                    if (CrmIncidentTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule Incident ticketNumber: '{0}'",im.ticketnumber),CrmIncidentTrace.Sw.Info);
                }
                catch (Exception ex)
                {
                    if (CrmIncidentTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputIncident CrmInputIncident_ADNUpdateModule Adding Incident ex :{0}", ex),CrmIncidentTrace.Sw.Info);
                    throw;
                }

                // Attached docs
                if (RadUpload1.UploadedFiles.Count > 0)
                {
                    foreach ( UploadedFile fi in RadUpload1.UploadedFiles )
                    {
                        string fileName     =   fi.GetName();
                        Stream istream      =   fi.InputStream;
                        AttachNote(im,fi);
                    }
                }


                // Assign to default owner
                if ( Settings[AStr.AssignToOwner].ToBool() )
                {
                    try
                    {
                        string str                  =   Settings[AStr.CrmInputIncidentOwner].Value;
                        if (CrmIncidentTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule  assigning Incident to owner id: '{0}'", str),CrmIncidentTrace.Sw.Info);
                        im.adminAssign(new Guid(str));
                        if (CrmIncidentTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident CrmInputIncident_ADNUpdateModule Incident assigned to owner id: '{0}'", str),CrmIncidentTrace.Sw.Info);
                    }
                    catch (Exception ex)
                    {
                        if (CrmIncidentTrace.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputIncident CrmInputIncident_ADNUpdateModule assigning Incident ex :{0}", ex),CrmIncidentTrace.Sw.Info);
                        throw;
                    }
                }
                clean();
            }
            catch (Exception ex)
            {
                if (CrmIncidentTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputIncident CrmInputIncident_ADNUpdateModule ex :{0}", ex),CrmIncidentTrace.Sw.Info);
                throw;
            }
        }
        
        /// <summary>
        /// re-initialized fields 
        /// </summary>
        protected void clean()
        {
            RadtxtTitle.Text            =   string.Empty;
            TbSerialNumber.Text         =   string.Empty;
            RadTextDescription.Text     =   string.Empty;
            ComboStatisfaction.ClearSelection();
            ComboPriority.ClearSelection();
            ComboOrigin.ClearSelection();
            ComboType.ClearSelection();
            DateFollowUp.Clear();
            ComboCustomer.ClearSelection();
            ComboCustomer.Text          =   string.Empty;
            ComboContract.ClearSelection();
            ComboContract.Text          =   string.Empty;
            ComboContractLine.ClearSelection();
            ComboContractLine.Text      =   string.Empty;
            ComboProduct.ClearSelection();
            ComboSubject.ClearSelection();
        }

        #endregion insert input in Crm

        #region radCombobox load handlers


        void LoadPickList(string pickListName,RadComboBox Combo)
        {
            string entityNm           =   CrmStr.incident;
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadPickList BEG entityNm: '{0}'.",
                    entityNm),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            try
            {
                string pickListDisplayName      =   Wrapper.Util.ExtractAttributeDisplayName(entityNm,pickListName);
                ArrayList Arl                   =   GetPickListArray(pickListName,entityNm);
                Combo.DataTextField         =   "name";
                Combo.DataValueField        =   "val";
                Combo.DataSource            =   Arl;
                Combo.DataBind();
                foreach (RadComboBoxItem item in Combo.Items)
                {
                    item.ToolTip            = item.Text;
                }
            }
            catch (Exception ex)
            {
                    if (CrmIncidentTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputIncident LoadPickList ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadPickList END Count: {0}",
                    Combo.Items.Count),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }

        void LoadLookup(string entityName, RadComboBox Combo,InternalConditionExpression c1)
        {
            Guid firstEntity        =   Guid.Empty;
            ArrayList ar            =   Wrapper.Util.PotentialEntities(entityName,c1,ref firstEntity,false);
            Combo.DataTextField     =   "name";
            Combo.DataValueField    =   "ID";
            Combo.DataSource        =   ar;
            Combo.DataBind();
            if ( firstEntity != Guid.Empty )
                Combo.SelectedValue     =   firstEntity.ToString();
        }

        void LoadCustomers()
        {
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]CrmInputIncident LoadCustomers BEG.",
                    (CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            try
            {
                if (!Settings[AStr.UseCustomerFilter].ToBool())
                    LoadLookup(CrmStr.account, ComboCustomer, null);
                else
                {
                    DataTable Tb                =   null;
                    if (!Settings[AStr.UserQueryMode].ToBool())
                    {
                        string FetchXml             =   Settings[AStr.CustomerFilter].Value;
                        string entityName           =   string.Empty;
                        if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadCustomers FetchXml: {0}",
                                FetchXml),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                        Tb                          =   Wrapper.Util.GetTableFromFetchXmlQuery(ResetWrapper,FetchXml,ref entityName,CrmStr.name,string.Empty,string.Empty,0,true);
                        if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadCustomers FentityName: {0}, Count: {1}",
                                entityName,(Tb!=null) ? Tb.Rows.Count:0),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                    }
                    else 
                    {
                        Guid QueryId                =   new Guid(Settings[AStr.UserQuery].Value);
                        if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadCustomers QueryId: {0}",
                                QueryId),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                        Tb                          =   Wrapper.Util.GetTableFromQuery(QueryId,ResetWrapper,true);
                        if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadCustomers Count: {0}",
                                (Tb!=null) ? Tb.Rows.Count:0),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                    }
                    if ( Tb != null )
                    {
                        ComboCustomer.DataTextField     =   CrmStr.name;
                        ComboCustomer.DataValueField    =   CrmStr.accountid;
                        ComboCustomer.DataSource        =   Tb;
                        ComboCustomer.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
                    if (CrmIncidentTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputIncident LoadCustomers ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadCustomers END Count: {0}",
                    ComboCustomer.Items.Count),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }

        void LoadContracts(string selCustomer)
        {
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadContracts BEG selCustomer: {0}.",
                    selCustomer),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            try
            {
                InternalConditionExpression c1  =   new InternalConditionExpression();
                c1.AttributeName                =   CrmStr.customerid;
                c1.Operator                     =    InternalConditionOperator.Equal;
                c1.Values                       =   new string[]{selCustomer};
                LoadLookup(CrmStr.contract,ComboContract,c1);
            }
            catch (Exception ex)
            {
                    if (CrmIncidentTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputIncident LoadContracts ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadContracts END Count: {0}",
                    ComboContract.Items.Count),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }

        void LoadContractLines(string selContract)
        {
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadContractLines BEG selContract: {0}.",
                    selContract),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            try
            {
                InternalConditionExpression c1  =   new InternalConditionExpression();
                c1.AttributeName                =   CrmStr.contractid;
                c1.Operator                     =    InternalConditionOperator.Equal;
                c1.Values                       =   new string[]{selContract};
                LoadLookup(CrmStr.contractdetail,ComboContractLine,c1);
            }
            catch (Exception ex)
            {
                    if (CrmIncidentTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputIncident LoadContractLines ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmIncidentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputIncident LoadContractLines END Count: {0}",
                    ComboContractLine.Items.Count),(CrmIncidentTrace.Sw.TraceVerbose)? CrmIncidentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }

        void ComboCustomer_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            LoadCustomers();
        }
        void ComboContract_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            LoadContracts(e.Text);
        }

        void ComboContractLine_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            LoadContractLines(e.Text);
        }
        
        #endregion radCombobox load handlers

        void ResetBtn_Click(object sender, ImageClickEventArgs e)
        {
            clean();
        }

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string loc          =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID    =   "Update_" + loc;
            ResetBtn.SkinID     =   "Reset_" + loc;
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                                        +=      new System.EventHandler(this.Page_Load);
            ADNUpdateModule                             +=      new PortalModuleEventHandler(CrmInputIncident_ADNUpdateModule);
            ResetBtn.Click                              +=      new ImageClickEventHandler(ResetBtn_Click);
            // Customers invisibles if autoassigned-> contracts also
            if ( Settings[AStr.AutoCustomer].ToBool() )
            {
                ComboCustomer.Visible                   =   false;
                Label1.Visible                          =   false;
                ComboContract.Visible                   =   false;
                Label9.Visible                          =   false;
                ComboContractLine.Visible               =   false;
                Label11.Visible                         =   false;
            }
            else
            {
                ComboCustomer.ItemsRequested            +=  new RadComboBoxItemsRequestedEventHandler(ComboCustomer_ItemsRequested);
                ComboCustomer.EnableLoadOnDemand        =   true;
                // Contracts not input
                if ( Settings[AStr.InputContract].ToBool() )
                {
                    ComboContract.Visible               =   false;
                    Label9.Visible                      =   false;
                    ComboContractLine.Visible           =   false;
                    Label11.Visible                     =   false;
                }
                else
                {
                    ComboContract.EnableLoadOnDemand    =   true;
                    ComboContract.ItemsRequested        +=  new RadComboBoxItemsRequestedEventHandler(ComboContract_ItemsRequested);
                    ComboContractLine.EnableLoadOnDemand=   true;
                    ComboContractLine.ItemsRequested    +=  new RadComboBoxItemsRequestedEventHandler(ComboContractLine_ItemsRequested);
                }
            }
        }

        #endregion Std overrides
    }
}
